package zzj.campus_book_sharing_platform.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import zzj.campus_book_sharing_platform.Dao.UserDao;
import zzj.campus_book_sharing_platform.Dao.postDao;
import zzj.campus_book_sharing_platform.Entity.Post;
import zzj.campus_book_sharing_platform.Entity.User;
import zzj.campus_book_sharing_platform.Service.PostService;
import zzj.campus_book_sharing_platform.domain.dto.PostDto;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

@Service
public class PostServiceImpl extends ServiceImpl<postDao, Post> implements PostService {
    @Resource
    private postDao postDao;

    @Resource
    private UserDao userDao;

    @Override
    public IPage queryAll(Integer currentPage) {
        Page page = new Page(currentPage, 4);
        IPage pageData = this.page(page, new QueryWrapper<Post>().orderByDesc("creat_time"));
        return pageData;
    }

    @Override
    public Post selectById(String postId) {
        Post post = postDao.selectById(postId);
        return post;
    }

    @Override
    public int insert(PostDto postDto, HttpSession session) {
        postDto.setUserId((String) session.getAttribute("userId"));
        postDto.setPostId(String.valueOf(UUID.randomUUID()));
        postDto.setCreatTime(new Date());
        if("exchange".equals(postDto.getTypePost())){
            postDto.setStatusPost("寻求交换中");
        }else{
            postDto.setStatusPost("对话中");
        }
        return postDao.insert(postDto);
    }

    @Override
    public int deleteById(String postId,HttpSession session) {
        String userId = (String) session.getAttribute("userId");
        User user = userDao.queryById(userId);
        if("1".equals(user.getPermissionsId())||postDao.selectById(postId).getUserId().equals(userId)) {
            return postDao.deleteById(postId);
        }
        return 0;
    }
}
